const Base = require('./base.js');

function compareLast(a, b) {
  return a.last - b.last;
}

module.exports = class extends Base {
  async indexAction() {
    return this.display();
  }

  async listAction() {
    const bittrexTickers = think.bittrexTickers;
    const gateTickers = think.gateTickers;
    const poloniexTickers = think.poloniexTickers;

    const allTickers = {};
    for (let i = 0; i < think.allBTCTrade.length; i++) {
      const market = think.allBTCTrade[i];

      const bVolume = bittrexTickers[market] ? bittrexTickers[market]['BaseVolume'] : 0;
      const gVolume = gateTickers[market] ? gateTickers[market]['baseVolume'] : 0;
      const pVolume = poloniexTickers[market] ? poloniexTickers[market]['BaseVolume'] : 0;
      const bLast = bittrexTickers[market] ? bittrexTickers[market]['Last'] : 0;
      const gLast = gateTickers[market] ? gateTickers[market]['last'] : 0;
      const pLast = poloniexTickers[market] ? poloniexTickers[market]['LastPrice'] : 0;
      let suggest = '-';
      let percent = 0;
      const marks = [];
      if (bLast > 0) {
        marks.push({name: 'B网', last: bLast});
      }
      if (gLast > 0) {
        marks.push({name: 'G网', last: gLast});
      }
      if (pLast > 0) {
        marks.push({name: 'C网', last: pLast});
      }
      if (marks.length > 1) {
        marks.sort(compareLast);
        suggest = marks[0].name + '      --->      ' + marks[marks.length - 1].name;
        percent = (marks[marks.length - 1].last / marks[0].last - 1) * 100;
      }
      const item = {
        market: market,
        bMarket_last: bLast,
        gMarket_last: gLast,
        pMarket_last: pLast,
        bBaseVolume: bVolume,
        gBaseVolume: gVolume,
        pBaseVolume: pVolume,
        suggest: suggest,
        percent: percent.toFixed(2)
      };
      if (marks.length > 1) {
        allTickers[market] = item;
      }
    }

    return this.success(allTickers);
  }
};
